package edu.ustb.efws.security.token;

import com.stoyanr.evictor.ConcurrentMapWithTimedEviction;
import com.stoyanr.evictor.map.ConcurrentHashMapWithTimedEviction;
import edu.ustb.efws.security.Credential;
import edu.ustb.efws.security.SecException;

/**
 * 基于内存实现{@link TokenService}
 *
 * @author TS Group
 */
public class MemTokenService implements TokenService {
    private static final ConcurrentMapWithTimedEviction<String, Credential> POOL = new ConcurrentHashMapWithTimedEviction<>();
    private final long expiredMs;

    public MemTokenService(){
       this(30 * 60 * 1000L);
    }

    public MemTokenService(long expiredMs){
        this.expiredMs = expiredMs;
    }

    @Override
    public String generate(Credential t) {
        String token = genToken();
        POOL.putIfAbsent(token, t, expiredMs);
        return token;
    }

    @Override
    public boolean update(String token, Credential t) {
        POOL.put(token, t, expiredMs);
        return true;
    }

    @Override
    public Credential validateAndGet(String token) {
        Credential t = POOL.get(token);
        if(t == null){
            throw new SecException(110, "认证不存在");
        }
        return t;
    }

    @Override
    public void destroy(String token) {
        POOL.remove(token);
    }
}
